import React, { useEffect, useRef, useState } from "react";
import BScroll from "better-scroll";
import PropTypes from "prop-types";

// https://blog.csdn.net/dhwmfzh624156/article/details/102319741
const Scroll = (props) => {
  const {
    x,
    y,
    onPullingUp,
    handleScroll,
    children,
    pullUpLoad,
    cname,
    probeType,
    isRefresh,
  } = props;
  const scrollRef = useRef(null);
  const [bScroll, setBScroll] = useState(null);
  useEffect(() => {
    let scroll = new BScroll(scrollRef.current, {
      click: true,
      mouseWheel: true,
      pullUpLoad: pullUpLoad,
      scrollY: y,
      scrollX: x,
      probeType: probeType,
      bounce: true,
      // probeType: 3,
      // click: click,
      // bounce: {
      //   top: bounceTop,
      //   bottom: bounceBottom,
      // },
    });

    probeType === 2 &&
      scroll.on("scroll", (e) => {
        handleScroll(e);
        console.log("handleScroll");
      });

    pullUpLoad &&
      scroll.on("pullingUp", () => {
        onPullingUp();
        console.log("onPullingUp");
      });

    setBScroll(scroll);
    return () => {
      destroy();
    };
  }, []);

  useEffect(() => {
    refresh();
  });

  const refresh = () => {
    console.log("refresh");
    bScroll && bScroll.refresh();
  };
  const finishPullUp = () => {
    bScroll && bScroll.finishPullUp();
  };
  const scrollToElement = (el, time, offsetX, offsetY, easing) => {
    bScroll && bScroll.scrollToElement(el, time, offsetX, offsetY, easing);
  };
  const scrollTo = (x, y, time = 200) => {
    bScroll && bScroll.scrollTo(x, y, time);
  };
  const destroy = () => {
    bScroll && bScroll.destroy();
    setBScroll(null);
  };
  const sty =
    cname && cname.length
      ? { overflow: "hidden" }
      : { width: "100%", height: "100%", overflow: "hidden" };
  return (
    <div ref={scrollRef} className={cname} style={sty}>
      <div>{children}</div>
    </div>
  );
};

Scroll.propTypes = {
  onPullingUp: PropTypes.func,
  handleScroll: PropTypes.func,
  x: PropTypes.bool,
  y: PropTypes.bool,
  pullUpLoad: PropTypes.bool,
  cname: PropTypes.string,
  probeType: PropTypes.number,
  isRefresh: PropTypes.bool,
  children: PropTypes.element
};
Scroll.defaultProps = {
  onPullingUp: () => { },
  handleScroll: () => { },
  x: false,
  y: true,
  pullUpLoad: true,
  cname: "",
  probeType: 0,
  isRefresh: false,
};

export default Scroll;
